import java.util.HashMap;
import java.util.Map;

/**
 * @program: LeetCode
 * @description: LeetCode : 剑指 Offer II 011. 0 和 1 个数相同的子数组
 * @author: WXY
 * @create: 2022-12-21 15:10
 * @Version 1.0
 **/

public class offer_four2_findMaxLength {
    public static int findMaxLength(int[] nums) {
        int ans = 0;
        int sum = 0;
        Map<Integer, Integer> map = new HashMap<>();
        map.put(sum, -1);
        for (int i = 0; i < nums.length; i++) {
            sum += nums[i] == 1 ? 1 : -1;
            if (map.containsKey(sum)) {
                ans = Math.max(i - map.get(sum), ans);
            } else {
                map.put(sum, i);
            }
        }
        return ans;
    }
}
